import React, { forwardRef, useMemo } from 'react';
import ReactEChartsCore from 'echarts-for-react/lib/core';
import * as echarts from 'echarts/core';
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
} from 'echarts/components';
import { BarChart as EBarChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';
import './index.scss';

echarts.use([TitleComponent, TooltipComponent, LegendComponent, GridComponent, EBarChart, CanvasRenderer]);

export interface BarChartDataItem {
  name: string;
  value: number;
}

export interface BarChartSeries {
  name: string;
  data: BarChartDataItem[];
  color?: string;
}

export interface BarChartProps {
  title?: string;
  xAxisData?: string[];
  series?: BarChartSeries[];
  width?: number | string;
  height?: number | string;
  theme?: 'light' | 'dark';
  showLegend?: boolean;
  showGrid?: boolean;
  showLabel?: boolean;
  barGap?: string;
  barWidth?: string | number;
  yAxisMax?: number;
  customOption?: any;
  onClick?: (params: any) => void;
  style?: React.CSSProperties;
  className?: string;
  __designMode?: string;
  componentId?: string;
  _componentName?: string;
  forwardRef?: any;
}

const BarChart = forwardRef<HTMLDivElement, BarChartProps>(({
                                                              title = '24小时人流统计',
                                                              xAxisData = Array.from({ length: 24 }, (_, i) => `${i}-${i + 1}点`),
                                                              series = [],
                                                              width = 500,
                                                              height = 224,
                                                              theme = 'dark',
                                                              showLegend = true,
                                                              showGrid = true,
                                                              showLabel = false,
                                                              barGap = '10%',
                                                              barWidth = 4,
                                                              yAxisMax = 20000,
                                                              customOption = {},
                                                              onClick,
                                                              style = {},
                                                              className = '',
                                                              ...otherProps
                                                            }, ref) => {
  const isDark = theme === 'dark';

  const colors = [
    new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      { offset: 0, color: '#58FFF6' },
      { offset: 1, color: 'rgba(0,255,241,0)' }
    ]),
    new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      { offset: 0, color: '#00D4FF' },
      { offset: 1, color: 'rgba(0,212,255,0)' }
    ])
  ];

  const option = useMemo(() => {
    return {
      color: colors,
      title: {
        text: title,
        left: 'left',
        top: 10,
        textStyle: {
          color: isDark ? '#FFFFFF' : '#333333',
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      backgroundColor: 'transparent',
      grid: {
        left: '60px',
        right: '40px',
        top: '60px',
        bottom: '60px',
        containLabel: false
      },
      legend: showLegend ? {
        data: series.map(s => s.name),
        top: 10,
        right: 40,
        textStyle: {
          color: isDark ? '#FFFFFF' : '#333333',
          fontSize: 12
        },
        itemWidth: 12,
        itemHeight: 12,
        itemGap: 20
      } : undefined,
      xAxis: {
        type: 'category',
        data: xAxisData,
        axisLabel: {
          color: isDark ? '#CCCCCC' : '#666666',
          fontSize: 10,
          rotate: 45,
          margin: 8
        },
        axisLine: {
          lineStyle: {
            color: isDark ? '#333333' : '#E0E0E0'
          }
        },
        axisTick: { show: false }
      },
      yAxis: {
        type: 'value',
        max: yAxisMax,
        interval: 5000,
        axisLabel: {
          color: isDark ? '#CCCCCC' : '#666666',
          fontSize: 12
        },
        axisLine: { show: false },
        axisTick: { show: false },
        splitLine: { show: false }
      },
      tooltip: {
        trigger: 'axis',
        backgroundColor: isDark ? 'rgba(0,0,0,0.8)' : 'rgba(255,255,255,0.9)',
        borderColor: isDark ? '#333' : '#E0E0E0',
        textStyle: {
          color: isDark ? '#FFF' : '#333',
          fontSize: 12
        },
        axisPointer: {
          type: 'shadow',
          shadowStyle: {
            color: isDark ? 'rgba(0, 212, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)'
          }
        }
      },
      series: series.map(s => ({
        name: s.name,
        type: 'bar',
        data: s.data.map(d => d.value),
        barWidth,
        barGap,
        itemStyle: {
          // color: s.color || (isDark ? '#00D4FF' : '#1890FF'),
          borderRadius: [2, 2, 0, 0]
        },
        label: showLabel ? {
          show: true,
          position: 'top',
          color: isDark ? '#FFFFFF' : '#333333',
          fontSize: 10
        } : undefined
      })),
      ...customOption
    };
  }, [title, xAxisData, series, showLegend, showLabel, barGap, barWidth, yAxisMax, customOption, isDark]);

  const containerStyle: React.CSSProperties = {
    width,
    height,
    ...style
  };

  return (
    <div
      ref={ref}
      className={`hzdz-bar-chart hzdz-bar-chart--${theme} ${className || ''}`}
      style={containerStyle}
      {...otherProps}
    >
      <ReactEChartsCore
        echarts={echarts}
        option={option}
        notMerge={true}
        lazyUpdate={true}
        style={{ width: '100%', height: '100%' }}
        onEvents={onClick ? { click: onClick } : undefined}
      />
    </div>
  );
});

BarChart.displayName = 'BarChart';

export default BarChart;
